package getlog

import (
	"fmt"
	"github.com/hpcloud/tail"
	"logagent/kafka"
	"time"
)

//专门从日志收集日志的模块
var (
	TailObj *tail.Tail
	line    *tail.Line
)

func TailfInit(fileName string) (TailObj *tail.Tail, err error) {
	config := tail.Config{
		ReOpen:    true,                                 //重新打开
		Follow:    true,                                 // 是否跟随
		Location:  &tail.SeekInfo{Offset: 0, Whence: 2}, //从文件哪个地方开始读
		MustExist: false,                                //文件不存在不报错
		Poll:      true,                                 //
	}
	TailObj, err = tail.TailFile(fileName, config)
	if err != nil {
		fmt.Println("tail file failed, err", err)
		return nil, err
	}
	fmt.Println("Succeed read file :", fileName)

	return TailObj, nil
}

func ReadLine(TailObj *tail.Tail, filename, topic string) {
	for {
		line, ok := <-TailObj.Lines //遍历chan，读取日志内容
		if !ok {
			fmt.Printf("tail file close reopen, filename:%s\n", filename)
			time.Sleep(time.Second)
			continue
		}
		data := fmt.Sprintf("[ %s ] => %s", filename, line.Text)
		kafka.SendtoKafka(topic, data)
	}
}

// QueueListOld := []string{"D:/learndj/test.log", "D:/learndj/event.log", "D:/learndj/package.log"}
func Ergodic(topic string, QueueListOld []string) {
	fmt.Println("本次的读取的日志有：", QueueListOld)
	for _, filename := range QueueListOld {
		tailobj, err := TailfInit(filename)
		if err != nil {
			fmt.Printf("get tailobj failed,err: %s", err)
		}
		go ReadLine(tailobj, filename, topic)
	}
}
